#include "tcpsocketdeom.h"
#include "ui_tcpsocketdeom.h"
#include <unistd.h>

TcpSocketDeom::TcpSocketDeom(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TcpSocketDeom)
{
    ui->setupUi(this);
    tcpServer = new QTcpServer(this);
    ui->Send_Button->setEnabled(false);
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnect_Slot()));
    times = 0;
}

TcpSocketDeom::~TcpSocketDeom()
{
    delete ui;
}

void TcpSocketDeom::newConnect_Slot()
{
    // 当有新用户连接时,获取连接套接字
    tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData()));
    ui->ClientIP->setText(QString("%1%2").arg("New Connect IP:").arg(tcpSocket->peerAddress().toString()));
    sleep(5);
    ui->ClientIP->clear();
}

void TcpSocketDeom::readData()
{
    // 但有接收数据时触发该函数，将接收数据显示到界面
    QByteArray tmpData = tcpSocket->read(1000);
    ui->reciveData_Edit->setText(QString::fromLatin1(tmpData.data(), strlen(tmpData.data())));
    ui->ClientIP->setText(QString("%1%2%3").arg("Recive Data To:").arg(tcpSocket->peerAddress().toString()).arg("Success!"));
    QString tmpTest = "WaitParameter";
    ui->SendData_Edit->setText(QString("%1%2").arg(QString::number(tcpSocket->write(tmpTest.toLocal8Bit().data()))).arg(times));
    times++;
}

void TcpSocketDeom::on_Listen_clicked()
{
    if(ui->Listen->text() == "Listen")
    {
        if(tcpServer->listen(QHostAddress::Any, ui->Port->text().toInt()))
        {
            ui->reciveData_Edit->setText(QString("port :%1%2").arg(ui->Port->text()).arg(" Listen Success!"));
            ui->Listen->setText("Dislisten");
            ui->Send_Button->setEnabled(true);
        }
        else
        {
            ui->ClientIP->setText(tcpServer->errorString());
            ui->Send_Button->setEnabled(false);
            return;
        }
    }
    else if(ui->Listen->text() == tr("Dislisten"))
    {
        tcpSocket->disconnectFromHost();
        tcpSocket = NULL;
        ui->Send_Button->setEnabled(false);
        tcpServer->close();
        ui->reciveData_Edit->setText(QString("port :%1%2").arg(ui->Port->text()).arg(" DisListen!"));
        ui->Listen->setText("Listen");
    }
}

void TcpSocketDeom::on_Send_Button_clicked()
{
    if(tcpSocket != NULL)
    {
        char *sendData = ui->SendData_Edit->toPlainText().toLatin1().data();
        tcpSocket->write(sendData, strlen(sendData));
        if(!tcpSocket->waitForBytesWritten(3000))
        {
            ui->ClientIP->setText(QString("%1%2%3").arg("Send Data To:").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->errorString()));
        }
        else
        {
            ui->ClientIP->setText(QString("%1%2%3").arg("Send Data To:").arg(tcpSocket->peerAddress().toString()).arg("Success!"));
        }
    }
}

void TcpSocketDeom::on_Connect_clicked()
{
   tcpSocket = NULL;
   tcpSocket = new QTcpSocket;
   bool isConnect = true;
   connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData()));
   tcpSocket->abort();
   tcpSocket->connectToHost(ui->IP->text(), ui->Port->text().toInt());
   if(!tcpSocket->waitForConnected())
   {
//       while (isConnect) {
//           tcpSocket->abort();
//           tcpSocket->connectToHost(ui->IP->text(), ui->Port->text().toInt());
//           if(tcpSocket->state() == tcpSocket->ConnectedState)
//           {
//               ui->ClientIP->setText(QString("%1%2%3%4").arg("Connect To :").arg(ui->IP->text()).arg(" Success.").arg(tcpSocket->errorString()));
//               ui->Send_Button->setEnabled(true);
//               isConnect = false;
//           }
//           else
//           {
               ui->ClientIP->setText(QString("%1%2%3%4").arg("Connect To :").arg(ui->IP->text()).arg(" Failed.").arg(tcpSocket->errorString()));
               ui->Send_Button->setEnabled(false);
//           }
//       }
   }
   else
   {
       ui->ClientIP->setText(QString("%1%2%3%4").arg("Connect To :").arg(ui->IP->text()).arg(" Success.").arg(tcpSocket->errorString()));
       ui->Send_Button->setEnabled(true);
   }
}
